import Decorator from '../core/Decorator';
import { FAILURE } from '../constants';
import Tick from '../core/Tick';
import BaseNode from '../core/BaseNode';
// 超出时间认定 失败
export default class MaxTime extends Decorator {

  maxTime: number

  constructor(child: BaseNode, maxTime: number) {
    super(`MaxTime[${maxTime}ms]`, child);
    this.addProperties('maxTime', maxTime)

    if (!maxTime) {
      throw 'maxTime parameter in MaxTime decorator is an obligatory parameter';
    }

    this.maxTime = maxTime;
  }

  onOpen(tick: Tick, ...args: any[]) {
    var startTime = (new Date()).getTime();
    tick.blackboard.set('startTime', startTime, tick.tree.id, this.id);
  }

  onTick(tick: Tick, ...args: any[]) {
    var currTime = (new Date()).getTime();
    var startTime = tick.blackboard.get('startTime', tick.tree.id, this.id);
    if (currTime - startTime > this.maxTime) {
      return FAILURE;
    }
    var status = this.child.execute(tick, ...args);
    return status;
  }
};
